//
//  VerifyViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/8/28.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SwiftyJSON

class VerifyViewController: KMViewController {

    var verifyView : VerifyView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.verifyColor()

        self.title = verifyName_title
        
        let licenseFile = Bundle.main.path(forResource: "aip", ofType: "license")
        let licenseFileData = NSData.init(contentsOfFile: licenseFile!)
        AipOcrService.shard().auth(withLicenseFileData: licenseFileData! as Data)
        
        createSubView()
    }
    
    //MARK: 创建子视图
    fileprivate func createSubView() {
        
        self.automaticallyAdjustsScrollViewInsets = false
        
        verifyView = VerifyView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 270)))
        verifyView.verifyBtn.addTarget(self, action: #selector(verifyAction), for: .touchUpInside)
        verifyView.imageButton.addTarget(self, action: #selector(verifyIDCard), for: .touchUpInside)
        self.view.addSubview(verifyView)
    }
    
    deinit {
        
        verifyView.marqueeView.timer.invalidate()
        verifyView.marqueeView.timer = nil
    }
    
    //MARK: 认证
    @objc fileprivate func verifyAction() {
        
        KMTool.requestMethod(.post, URLString: url_verify, parameters: ["user_name":KMTool.stringForEnumKey(.phone) ?? "","name":verifyView.nameText.text!,"idcard":verifyView.numberText.text!], success: { (value, json) in
            
            if json["status"] == "0" {
                KMTool.showText(_text: json["msg"].stringValue)
                KMTool.setObject(json["auth"].stringValue, forEnumKey: .verify)
                self.navigationController?.popViewController(animated: true)
            }else{
                KMTool.showText(_text: json["msg"].stringValue)
            }
        }) {
            
        }
    }
    
    //MARK: 识别身份证
    @objc fileprivate func verifyIDCard() {
        
        let vc = AipCaptureCardVC.viewController(with: .idCardFont) { (image) in
            
            //成功扫描身份证
            AipOcrService.shard().detectIdCardFront(from: image, withOptions: nil, successHandler: { (result) in
                
                let dic = JSON.init(result!)
//                MyLog(dic)
                
                let idNumber = dic["words_result"]["公民身份号码"]["words"].stringValue
                let name = dic["words_result"]["姓名"]["words"].stringValue
              
                //主线程刷新UI
                DispatchQueue.main.async(execute: {
                    self.verifyView.numberText.text = idNumber
                    self.verifyView.nameText.text = name
                    self.dismiss(animated: true, completion: nil)
                })
                
                
            }, failHandler: { (error) in
                MyLog(error.debugDescription)
                
                //主线程刷新UI
                DispatchQueue.main.async(execute: {
                    KMTool.showText(_text: failToRecognized)
                    self.dismiss(animated: true, completion: nil)
                })
                
            })
            
        }
        
        
        self.present(vc!, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
